import collections
import os
import sys
import getopt

from checker.dead_link_check import check_target_link_for_single_url, check_target_link_for_local_file, \
    check_target_link_for_local_repos, clone_and_check_for_repo_url, clone_and_check_for_organization_repos
from checker.utils import get_date
from checker.utils_config import init_global_config_setting, init_output_path

COMMAND_DICT = collections.defaultdict(list)
PARAMETER_DICT = init_global_config_setting()  # 记录个性化参数配置


def launch_checker(argv):
    handle_argv(argv)
    check_as_command()


def handle_argv(argv):
    if not argv:
        print_help_info()
    try:
        opts, args = getopt.getopt(argv, 'hu:f:d:r:o:',
                                   ['help', 'url=', 'file_path=', 'dir_path=',
                                    'repo_url=', 'organization=', 'branch=',
                                    'closed_repo', 'missed_anchor', 'just_all_link'])
    except getopt.GetoptError:
        print_error_info(argv)
    else:
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                print_help_info()
            elif opt in ('-u', '--url'):
                COMMAND_DICT['url'].append(arg)
            elif opt in ('-f', '--file_path'):
                COMMAND_DICT['file_path'].append(arg)
            elif opt in ('-d', '--dir_path'):
                COMMAND_DICT['dir_path'].append(arg)
            elif opt in ('-r', '--repo_url'):
                COMMAND_DICT['repo_url'].append(arg)
            elif opt in ('-o', '--organization'):
                COMMAND_DICT['organization'].append(arg)
            elif opt in ('--branch',):
                PARAMETER_DICT['branch_or_tag'] = arg
            elif opt in ('--closed_repo', '--missed_anchor', '--just_all_link'):
                PARAMETER_DICT[opt[2:]] = True


def check_as_command():
    record_dict = {
        'url': {'file_mark': '_md链接_目标链排查结果报告_', 'check_func': check_target_link_for_single_url},
        'file_path': {'file_mark': '_本地文件_目标链排查结果报告_', 'check_func': check_target_link_for_local_file},
        'dir_path': {'file_mark': '_本地仓库_目标链排查结果报告_', 'check_func': check_target_link_for_local_repos},
        'repo_url': {'file_mark': '_链接仓库_目标链排查结果报告_', 'check_func': clone_and_check_for_repo_url},
        'organization': {'file_mark': '_组织仓库_目标链排查结果报告_', 'check_func': clone_and_check_for_organization_repos},
    }

    output_path = init_output_path()
    for opt, args in COMMAND_DICT.items():
        for arg in args:
            suffix = str(hash(arg))[-5:]
            output_file_name = os.path.join(output_path,
                                            get_date() + record_dict[opt]['file_mark'] + suffix + '.xlsx')
            record_dict[opt]['check_func'](arg, output_file_name)


def print_help_info():
    help_info = """
usage: check.py  [-h | --help] [-u | --url=<md_url>] 
                 [-f | --file_path=<file_path>] [-d | --dir_path=<dir_path>] 
                 [-r | --repo_url=<repo_url>] [-o | --organization=<organization>]
                 [--branch=<branch_or_tag>]
                 [--closed_repo] [--missed_anchor] [--just_all_link] 
                             
支持排查场景如下:
   
1. 检查文档URL中的目标链
    python check.py -u <url_need_to_check> [--<customized_choice>...]
    
2. 检查本地文档文件中的目标链 
    python check.py -f <file_path_need_to_check> [--<customized_choice>...]
    
3. 检查本地仓库中多有文档文件中的目标链 
    python check.py -d <dir_path_need_to_check> [--<customized_choice>...]
    
4. 传入仓库URL，自动clone，并排查目标链
    python check.py -r <repo_url_need_to_check> [--<customized_choice>...]
    
5. 传入Gitee社区组织名，自动clone，排查组织目标链
    python check.py -o <organization_need_to_check> [--<customized_choice>...] 
    
    """
    print(help_info)
    sys.exit()


def print_error_info(argv):
    argument = ' '.join(argv)
    error_info = f'\'python check.py {argument}\' is not a legitimate command. ' \
                 f'\nSee \'python check.py --help\'.'
    print(error_info)
    sys.exit()


if __name__ == '__main__':
    cmd = ['-o', 'openharmony-retired', '--closed_repo']
    launch_checker(cmd)
